package com.budwk.app.sqfw.services.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.text.StrFormatter;
import com.budwk.app.sms.dto.SmsMsgDTO;
import com.budwk.app.sms.service.OpaSmsService;
import com.budwk.app.sqfw.constants.SqfwCloudBusinessConstants;
import com.budwk.app.sqfw.constants.SqfwFormSummaryConstants;
import com.budwk.app.sqfw.enums.CompleteFlowFileTypeEnum;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfw.models.*;
import com.budwk.app.sqfw.services.*;
import com.budwk.app.sqfw.tencent.TCyysb;
import com.budwk.app.sqfwV2.service.ShopsBaseInfoService;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.database.service.BaseServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.trans.Trans;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@IocBean(args = {"refer:dao"})
public class SqfwCompleteflowServiceImpl extends BaseServiceImpl<Sqfw_completeflow> implements SqfwCompleteflowService {
    public SqfwCompleteflowServiceImpl(Dao dao) {
        super(dao);
    }

    @Inject
    private SqfwCloudcallbackService sqfwCloudcallbackService;
    @Inject
    private OpaSmsService opaSmsService;
    @Inject
    private SqfwServicerecordService sqfwServicerecordService;
    @Inject
    private SysUserService sysUserService;
    @Inject
    private HuaweiOssService huaweiOssService;
    @Inject
    private PropertiesProxy propertiesProxy;
    @Inject
    private SqfwFormSummaryService sqfwFormSummaryService;
    @Inject
    private SqfwFormsummaryNewService sqfwFormsummaryNewService;
    @Inject
    private SqfwWorkorderService sqfwWorkorderService;

    @Inject
    private ShopsBaseInfoService shopsBaseInfoService;

    public int transferFlowAudioToText(String id) {
        // 首先去回调表中查询数据 如果已经存在则不能继续操作
        boolean canTransferFlag = true;
        List<Sqfw_cloudcallback> cloudCallBackList = sqfwCloudcallbackService.query(Cnd.where(Sqfw_cloudcallback::getBusinessType, "=", SqfwCloudBusinessConstants.FLOW)
                .and(Sqfw_cloudcallback::getBusinessId, "=", id));
        for (Sqfw_cloudcallback existCallBack : cloudCallBackList) {
            if (existCallBack.getCode().equals("0")) {
                canTransferFlag = false;
                break;
            }
        }

        if (!canTransferFlag) return 0;

        Sqfw_completeflow completeFlow = fetch(id);
        if (completeFlow == null) return 0;
        if (!completeFlow.getFileType().contains(CompleteFlowFileTypeEnum.SOUND_RECORD.getName())) return 0;

        // 向腾讯发送一条数据
        String url = huaweiOssService.getPwdPath(completeFlow.getResourcePath());
        String serviceIp = propertiesProxy.get("jarService.ip");
        String port = propertiesProxy.get("server.port");
        String callback = StrFormatter.format("http://{}:{}/platform/sqfw/cloudcallback/callbackForCommon", serviceIp, port);
        Long taskId = TCyysb.Send(url, callback);

        // 往语音回调表中插入一条数据
        String cloudCallBackId = sqfwCloudcallbackService.preInsertSqfwCloudCallBack(SqfwCloudBusinessConstants.FLOW, id, taskId + "");
        return StringUtils.isBlank(cloudCallBackId) ? 0 : 1;
    }

    @Override
    public int flowTakeAPatSms(String serviceOrderId, String serviceUserId) {

        Sqfw_servicerecord serviceRecord = sqfwServicerecordService.fetch(serviceOrderId);
        if (serviceRecord == null) return 0;

        Sys_user serviceUser = sysUserService.fetch(serviceUserId);
        if (serviceUser == null) return 0;

        Sys_user createServiceOrderUser = sysUserService.fetch(serviceRecord.getCreatedBy());

        String msgStr = StrFormatter.format("{}在任务“{}”中拍了拍您", serviceUser.getUsername(), serviceRecord.getCustomer_need());

        SmsMsgDTO msgDTO = new SmsMsgDTO();
        msgDTO.setPhoneNumberSet(Sets.newHashSet(createServiceOrderUser.getLoginname()));
        msgDTO.setTemplateParamList(Lists.newArrayList(msgStr));
        return opaSmsService.opaSmsSendOneMessage(msgDTO);
    }

    @Override
    public Pagination getFireHiddenPDFByPhoneNo(String phoneNo, int pageNo, int pageSize) {
        Cnd formSummaryCnd = Cnd.NEW();
        formSummaryCnd.or(Sqfw_formSummary::getA8, "=", phoneNo);
        formSummaryCnd.or(Sqfw_formSummary::getA4, "=", phoneNo);//威清门的电话号码是 a4 字段
        formSummaryCnd.desc(Sqfw_formSummary::getFillDate);
        List<String> typeList= Arrays.asList(SupportBusinessTypeEnum.SAFE_CHECK.getName(),SupportBusinessTypeEnum.SAFETY_CHECK.getName());
        List<Sqfw_formSummary> formSummaryList = sqfwFormSummaryService.query(formSummaryCnd);
        List<Sqfw_formSummary_new> formSummaryNewList = sqfwFormsummaryNewService.query(Cnd.where(" param_data->>'operatorTelephone'", "=", phoneNo)
                .and(Sqfw_formSummary_new::getType, "in", typeList));
        List<String> sqfwFlowIdList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(formSummaryList)) {
            sqfwFlowIdList = formSummaryList.stream().map(Sqfw_formSummary::getSqfwFlowId).collect(Collectors.toList());
        }
        if (CollectionUtil.isNotEmpty(formSummaryNewList)) {
            sqfwFlowIdList.addAll(formSummaryNewList.stream().map(Sqfw_formSummary_new::getSqfwFlowId).collect(Collectors.toList()));
        }
        Cnd cnd = Cnd.where(Sqfw_completeflow::getId, "in", sqfwFlowIdList)
                .and(Sqfw_completeflow::getResourcePath, "!=", "creating")
                .and(Sqfw_completeflow::getResourcePath, "!=", "error");
        cnd.desc(Sqfw_completeflow::getCreateDate);
        Pagination pagination = listPage(pageNo, pageSize, cnd);
        List<Sqfw_completeflow> list = pagination.getList(Sqfw_completeflow.class);
        pagination.setList(list);
        return pagination;
    }

    @Override
    public void insertCompleteflow(Sqfw_completeflow completeflow, Sys_user sysUser) {
        // 默认填写以下信息
        completeflow.setCreateDate(new Date())
                .setUserName(sysUser.getUsername())
                .setUserId(sysUser.getId());
        insert(completeflow);
    }

    @Override
    public void deleteAndUpdateWO(String sqfwFlowId) {
        Sqfw_completeflow completeFlow = fetch(sqfwFlowId);
        if (completeFlow == null) {
            return;
        }

        Trans.exec(() -> {
            // 删除工作流
            delete(sqfwFlowId);

            String workerId = completeFlow.getWorkerId();

            // 更改对应的工单状态
            Cnd lastCnd = Cnd.NEW();
            lastCnd.and(Sqfw_completeflow::getWorkerId, "=", completeFlow.getWorkerId()).and(Sqfw_completeflow::getId, "!=", sqfwFlowId);
            lastCnd.desc(Sqfw_completeflow::getCreateDate);
            Sqfw_completeflow lastCompleteFlow = fetch(lastCnd);

            // 更新对应工单的最新工作流备注
            String lastServiceType = "";
            if (lastCompleteFlow != null) lastServiceType = lastCompleteFlow.getFileType();
            sqfwWorkorderService.updateLatestFlowRemarkWithCompleteFlow(workerId, lastServiceType, false);

            // 删除对应的formSummary表的数据
            List<Sqfw_formSummary> formSummaryList = sqfwFormSummaryService.query(Cnd.where(Sqfw_formSummary::getSqfwFlowId, "=", sqfwFlowId));
            if (formSummaryList.size() > 0)
                formSummaryList.forEach(item -> {
                            // wzy 2023-11-7 当删除 入户调查的 含有pdf的工作流时，需要做一些处理 需要删除人员表的数据
                            if (item.getType().equals(SqfwFormSummaryConstants.house_survey_form))
                                sqfwFormSummaryService.handleFormSummaryAndCenSusPaperForHouseSurveyDelete(item);
                            sqfwFormSummaryService.delete(item.getId());
                        }
                );

            // wzy 2024-1-18 添加下面的删除
            List<Sqfw_formSummary_new> formSummaryNewList = sqfwFormsummaryNewService.query(Cnd.where(Sqfw_formSummary_new::getSqfwFlowId, "=", sqfwFlowId));
            if (formSummaryNewList.size() > 0) {
                formSummaryNewList.forEach(item -> {
                    //zhangp 2024-03-08 删除商铺信息
                    //shopsBaseInfoService.deletedShopInfo(item);//2.0店铺信息已独立出来，因此删除最后一条记录时不删除对应店铺
                    sqfwFormsummaryNewService.delete(item.getId());
                });
            }
        });
    }
}
